package com.platform.core.security.auth;

import com.platform.comm.util.CommonWriter;
import com.platform.comm.web.results.JsonResult;
import com.platform.config.properties.CustomSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.platform.core.utils.RequestUtil.matchers;
import static com.platform.kaptcha.handler.CaptchaHandler.VALIDATE_CODE_PREFIX;

/**
 * Description: 验证码验证
 *
 * @author sunzhubin.zh Created on 2019/7/17
 **/
@Component
@Slf4j
public class VerifyAuthenticationFilter extends OncePerRequestFilter {

    private final CustomSecurityProperties securityProperties;
    private final RedisTemplate<String, Object> redisTemplate;

    public VerifyAuthenticationFilter(CustomSecurityProperties securityProperties, RedisTemplate<String, Object> redisTemplate) {
        this.securityProperties = securityProperties;
        this.redisTemplate = redisTemplate;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 验证码校验
        if (securityProperties.isEnableCaptcha()
                && matchers("/oauth/token", request)
                && StringUtils.equals(request.getParameter("grant_type"), "password")) {
            String uuid = request.getParameter("uuid");
            String verycode = request.getParameter("verycode");
            String value = (String) redisTemplate.opsForValue().get(VALIDATE_CODE_PREFIX + uuid);
            if (!StringUtils.isBlank(verycode)
                    && !StringUtils.isBlank(value)
                    && !StringUtils.equals(verycode, value)) {
                CommonWriter.write(JsonResult.failed("验证码错误"), response);
            }
        }

        filterChain.doFilter(request, response);
    }

}
